﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using ApiBetaSeries;
using ApiBetaSeries.Services;
using ApiBetaSeries.Factories;


namespace TestForms
{
    public partial class Form1 : Form
    {
        public string token;

        public Form1()
        {
            BetaSeriesConfig.ApiKey = "1330c9410051";

            InitializeComponent();
            login.Text = "albator1932";
            password.Text = "aspirin6";
            panel1.Enabled = false;
        }

        private void btnAuth_Click_1(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            Uri authUrl = new Uri("http://api.betaseries.com/members/auth.xml?key=1330c9410051&&login=" + login.Text + "&&password=" + GetMD5Hash(password.Text));
            string myXmlString = GetPageAsString(authUrl);

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(myXmlString);

            XmlNodeList xnList = xml.SelectNodes("/root/member");
            foreach (XmlNode xn in xnList)
            {
                //login = xn["login"].InnerText;
                token = xn["token"].InnerText;
            }
            btnAuth.Text = token;
            btnAuth.Enabled = false;
            login.Enabled = false;
            password.Enabled = false;

            UserServices userServ = UserServices.GetInstance();
            IUser user = userServ.GetInfos(token);

            List<IShowUser> userShows = user.Shows;
            foreach (IShowUser show in userShows)
            {
                lstShowsUser.Items.Add(show.Title);
                lstUrlUserShows.Items.Add(show.Url);
            }
            panel1.Enabled = true;
            this.Cursor = Cursors.Default;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (txtSearch.Text.Length >= 3)
            {
                this.Cursor = Cursors.WaitCursor;
                lstSearch.Items.Clear();
                lstUrlSearch.Items.Clear();
                txtNbSearch.Text = null;
                ShowServices showServ = ShowServices.GetInstance();
                Dictionary<string, string> showSearch = showServ.SearchShow(txtSearch.Text);
                foreach (KeyValuePair<string, string> kvp in showSearch)
                {
                    lstSearch.Items.Add(kvp.Key);
                    lstUrlSearch.Items.Add(kvp.Value);
                }
                txtNbSearch.Text = showSearch.Count.ToString() + " results";
                this.Cursor = Cursors.Default;
            }
            else
            {
                MessageBox.Show("Votre critère de recherche doit faire au moins 3 caractères.", "Erreur");
            }
        }

        public static string GetPageAsString(Uri address)
        {
            string result = "";
            HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                result = reader.ReadToEnd();
            }
            return result;
        }

        public static string GetMD5Hash(string input)
        {
            MD5 md5Hash = MD5.Create();
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            UserServices userServ = UserServices.GetInstance();
            ShowServices showServ = ShowServices.GetInstance();
            IShow show = ShowFactory.CreateShow();
            show = showServ.GetShow(lstUrlSearch.Items[lstSearch.SelectedIndex].ToString());
            userServ.AddShowInUser(token, show);

            // Rechargement de la liste
            lstShowsUser.Items.Clear();
            lstUrlUserShows.Items.Clear();
            IUser user = userServ.GetInfos(token);
            List<IShowUser> userShows = user.Shows;
            foreach (IShowUser showuser in userShows)
            {
                lstShowsUser.Items.Add(showuser.Title);
                lstUrlUserShows.Items.Add(showuser.Url);
            }
            this.Cursor = Cursors.Default;
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            UserServices userServ = UserServices.GetInstance();
            ShowServices showServ = ShowServices.GetInstance();
            IShow show = ShowFactory.CreateShow();
            show = showServ.GetShow(lstUrlUserShows.Items[lstShowsUser.SelectedIndex].ToString());
            userServ.DelShowInUser(token, show);
            lstUrlUserShows.Items.RemoveAt(lstShowsUser.SelectedIndex);

            // Rechargement de la liste
            lstShowsUser.Items.Clear();
            lstUrlUserShows.Items.Clear();
            IUser user = userServ.GetInfos(token);
            List<IShowUser> userShows = user.Shows;
            foreach (IShowUser showuser in userShows)
            {
                lstShowsUser.Items.Add(showuser.Title);
                lstUrlUserShows.Items.Add(showuser.Url);
            }
            this.Cursor = Cursors.Default;
        }

        private void btnMore_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            lstEpisodes.Items.Clear();
            lstSeasons.Items.Clear();

            txtUrlSearch.Text = lstUrlSearch.Items[lstSearch.SelectedIndex].ToString();
            SeasonServices seasonServ = SeasonServices.GetInstance();
            List<ISeason> seasonsList = seasonServ.GetSeasons(txtUrlSearch.Text, token);
            foreach (ISeason season in seasonsList)
            {
                lstSeasons.Items.Add(season);
                EpisodeServices episodeServ = EpisodeServices.GetInstance();
                List<IEpisode> episodesList = season.Episodes;
                foreach (IEpisode episode in episodesList)
                {
                    lstEpisodes.Items.Add(episode);
                }
            }
            this.Cursor = Cursors.Default;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }



    }
}
